<?php
	namespace Util;
	class LockCode{
		static private function Uuid_Key_Mapping(){
			return $KEY_UUID = array('H','3','Q','x','Y','7','S','V','p','T');
		}

		static private function Position_Key_Mapping(){
			return $KEY_POSITION = array('1','C','d','F','7','E','y','Y','8','K');
		}
		/**
		 * [lock 固定码输入加密]
		 * @Author   :seven
		 * @DateTime :2016-05-11T18:53:46+0800
		 * @Detail   :
		 * @param    [type]                    $uid    [description]
		 * @param    integer                   $Length [description]
		 * @return   [type]                            [description]
		 */
		static public function lock($uid,$Length = 24){
			/*经过测试超过一小时不用才会重新刷新,可以续签*/
			if(!$CODE){
				$KEY_UID = self::Uuid_Key_Mapping();
				$KEY_POSITION = self::Position_Key_Mapping();

				/*12位固定生成数字*/
				$Length -= 12;
				import('ORG.Util.String');
				$CODE = \Org\Util\String::randString(11,0);

				$U_POSITION = \Org\Util\String::randString(1,1);

				//后面生成的数据
				$CODE .= \Org\Util\String::randString($Length-strlen($uid),0,'0123456789');
				
				//UUID定位符
				$KEY_POS = $KEY_POSITION[$U_POSITION];
				$CODE.= $KEY_POS;

				//加密UUID
				for ($i=0; $i < strlen($uid); $i++) { 
					$UUID .= $KEY_UID[$uid[$i]];
				}
				
				//插入UUID
				$CODE = LockCode::insert2String($CODE,$U_POSITION,$UUID);
				//UUID长度添加
				$UUID_LENGTH = $KEY_UID[strlen($uid)];
			}

			return $CODE;
		}
		/**
		 * [unlockUUID 获取固定码(用户ID)]
		 * @Author   :seven
		 * @DateTime :2016-05-11T18:51:56+0800
		 * @Detail   :
		 * @param    [type]                    $CODE        [Lock Code]
		 * @param    [type]                    $UUID_LENGTH [Code Length]
		 * @return   [type]                                 [Unlock Code]
		 */
		static public function unlock($CODE,$UUID_LENGTH){
			if($UUID_LENGTH){
				/*查询UUID插入位置*/
				$POSITION = $CODE[strlen($CODE)-1];

				/*获取数据地图*/
				$POSITION_KEY = array_flip(self::Position_Key_Mapping());
				$UUID_KEY = array_flip(self::Uuid_Key_Mapping());
				/*查询保存的数据段*/
				$UUID = '';
				for ($i=$POSITION_KEY[$POSITION]; $i < $POSITION_KEY[$POSITION]+$UUID_LENGTH; $i++) { 
					$UUID .= $UUID_KEY[$CODE[$i]];
				}
				if(strlen($UUID) != $UUID_LENGTH){
					echo "ERR:DANGEROUS DATA";
					return "dangerous_err";
				}
			}else{
				echo 'ERR:UNLOCK UUID ERROR';
				exit;
			}

			return $UUID;
		}

		static public function insert2String($target,$index,$elem){
	        if($index > strlen($target)){
	            return "Err:Over index";
	        }
	        if($index == 0){
	            return $elem.$target;
	        }elseif($index == strlen($target)){
	            return $target.$elem;
	        }

	        $s_str = '';
	        for ($i=0; $i < $index; $i++) { 
	            $s_str .= $target[$i];
	        }

	        $e_str = '';
	        for ($i=$index; $i < strlen($target); $i++) { 
	            $e_str .= $target[$i];
	        }

	        return $s_str.$elem.$e_str;
	    }
	}
	?>